package ShiYan2;

import seventhweek.LinkedBinaryTree;

public class PreIntree {
    public LinkedBinaryTree<String> InPreTree(String inorder[],String preorder[]){
        LinkedBinaryTree<String> binaryTree;
        if (inorder.length == 0 || preorder.length == 0 || inorder.length != preorder.length) {
            binaryTree = new LinkedBinaryTree<>();
        }else {
            int num = 0;
            while (!inorder[num].equals(preorder[0])) {
                num++;
            }
            String[] preLeft = new String[num];
            String[] inLeft = new String[num];
            String[] preRight = new String[preorder.length - num - 1];
            String[] inRight = new String[inorder.length - num - 1];
            for (int temp = 0; temp < inorder.length; temp++) {
                if (temp < num) {
                    preLeft[temp] = preorder[temp + 1];
                    inLeft[temp] = inorder[temp];
                } else if (temp > num) {
                    preRight[temp - num - 1] = preorder[temp];
                    inRight[temp - num - 1] = inorder[temp];
                }else if(temp == num){
                    continue;
                }
            }
            LinkedBinaryTree<String> left = InPreTree(inLeft, preLeft);
            LinkedBinaryTree<String> right = InPreTree(inRight, preRight);
            binaryTree = new LinkedBinaryTree<String>(preorder[0], left, right);
        }
        return binaryTree;
    }
}